import {Component, OnInit} from '@angular/core';
import {environment} from "../../../environments/environment";
import {FileUploader} from "ng2-file-upload";
import {ConfirmationService} from "primeng/primeng";
import {InspectionService} from "../inspection.service";

@Component({
  selector: 'app-inspection-object',
  templateUrl: './inspection-object.component.html',
  styleUrls: ['./inspection-object.component.scss']
})
export class InspectionObjectComponent implements OnInit {
  showAddMask: boolean = false;
  cols;                             //声明表格表头
  showImportMask: boolean = false; //批量导入弹出框
  hasBaseDropZoneOver: boolean = false;
  hasAnotherDropZoneOver: boolean = false;
  display = false;
  totalRecords: number;
  currentInpection;
  assets;
  chooseCids =[];
  inspectionsObject;
  queryModel;
  selectInsepections=[];
  uploader: FileUploader;
  dataSource;
  constructor(
    private inspectionService: InspectionService,
    private confirmationService:ConfirmationService,

  ) {}

  ngOnInit() {
    this.uploader = new FileUploader({url: `${environment.url.management}/inspection/upload_inspection_object`});
    this.queryModel={
      "condition":{
        "region":"",
        "object":"",
        "content":"",
      },
      "page":{
        "page_size":"10",
        "page_number":"1"
      }
    };
    this.cols = [
      {field: 'region', header: '区域'},
      {field: 'object', header: '巡检对象'},
      {field: 'content', header: '巡检内容'},
      {field: 'object_type', header: '类型'},
      {field: 'reference_value', header: '参考值'},
    ]
    this.queryInsepection();
    this.uploader.onCompleteItem = (item: any, response:any, status:any, headers:any) => {
      console.log(response);
      if(response.search("{")===-1) {
        this.confirmationService.confirm({
          message: '请导入excel文件',
          rejectVisible:false,
        })
        return
      }
      let body = JSON.parse(response);
      if(body.errcode==='00000'){
        this.confirmationService.confirm({
          message: '导入数据成功！',
          rejectVisible:false,
        })
        this.queryInsepection();
      }else{
        this.confirmationService.confirm({
          message:body['errmsg'],
          rejectVisible:false
        })
        return
      }
      this.dataSource = body.datas;
      if(this.dataSource){
        this.totalRecords = this.dataSource.length;
        this.assets = this.dataSource.slice(0,10);
      }else{
        this.totalRecords = 0;
        this.assets = []
      }
    }

    /*
    this.uploader.onCompleteItem = (item: any, response:any, status:any, headers:any) => {


      if(response.search("{")===-1) {
        this.confirmationService.confirm({
          message: '请导入excel文件',
          rejectVisible:false,
        })
        return
      }
      let body = JSON.parse(response);
      if(body.errcode==='00000'){
        if(body.errmsg){
          this.confirmationService.confirm({
            message: '导入数据成功！',
            rejectVisible:false,
          });
          return
        }else{
          this.confirmationService.confirm({
            message:body['errmsg'],
            rejectVisible:false
          })
          return
        }
        this.dataSource = body.datas;
        if(this.dataSource){
          this.totalRecords = this.dataSource.length;
          this.assets = this.dataSource.slice(0,10);
        }else{
          this.totalRecords = 0;
          this.assets = []
        }
      }
      //   // this.queryInsepection();
      //   // this.confirmationService.confirm({
      //   //   message: '导入成功！',
      //   //   rejectVisible:false,
      //   // })
      // }else{
      //     this.confirmationService.confirm({
      //       message: body.errmsg,
      //       rejectVisible:false,
      //     })
      // }

    }
  */
  }
//打开遮罩层
  updateOption(currentInspection){
    this.currentInpection = currentInspection;
    this.showAddMask = !this.showAddMask;
  }
  closeInspectionMask(bool){
    this.showAddMask = bool;
  }
  //批量上传
  public fileOverBase(e:any):void {
    console.log(e)
  this.hasBaseDropZoneOver = e;
  }
  public fileOverAnother(e:any):void {
    console.log(e)
  this.hasAnotherDropZoneOver = e;
  }
//批量导入
  showImport(){
    this.showImportMask = !this.showImportMask;
    this.display = true;
  }
  closeImportMask(){
    this.showImportMask =!this.showImportMask;
  }
  //下载模板
  exportExcel(){
    //http://ip/data/file/inspection/download/批量导入巡检对象模板.xlsx
    window.location.href = `${environment.url.management}/data/file/inspection/download/批量导入巡检对象模板.xlsx`
  }
  //分页查询
  paginate(event) {
    this.chooseCids =[]
    this.queryModel.page.page_number = String(++event.page);
    this.queryModel.page.page_size = String(event.rows);
    this.queryInsepection()
  }
  //查询巡检对象库
  queryInsepection(){
    this.inspectionService.queryInspectionObject(this.queryModel).subscribe(data=>{
      this.inspectionsObject = data.items;
      this.totalRecords = data.page.total;
      if(!this.inspectionsObject){
        this.inspectionsObject = [];
        this.selectInsepections =[]
      }
    });
  }
  updateInsepectionObject(bool){
    this.queryInsepection();
    this.showAddMask = bool
  }
  //删除功能
  deleteInspection(){
    for(let i = 0;i<this.selectInsepections.length;i++){
      this.chooseCids.push(this.selectInsepections[i]['cid'])
    }
    this.confirmationService.confirm({
      message:'确认删除吗？',
      accept: () => {
        this.inspectionService.deleteInspectionObject(this.chooseCids).subscribe(()=>{
          this.queryInsepection();
          this.selectInsepections = [];
        },(err:Error)=>{
          let message ;
          if(JSON.parse(JSON.stringify(err)).status===0||JSON.parse(JSON.stringify(err)).status===504){
            message = '似乎网络出现了问题，请联系管理员或稍后重试'
          }else{
            message = err
          }
          this.confirmationService.confirm({
            message: message,
            rejectVisible:false,
          })
        })
      },
      reject:() =>{

      }
    })
    //请求成功后删除本地数据
  }
}

